import { useDeepCompareEffect } from 'ahooks';
import { Space, Typography } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import styles from './index.less';
import PickerModal from './PickerModal';

const nameObj = {
  market: '市场',
  city: '城市',
  area: '城区',
  district: '城区',
  store: '门店',
};

type TProps = {
  value?: Record<string, TIdNameData[]>;
  onChange?: TAnyFunction;
  left?: number;
  stepThreeRef?: any;
};

const CommonDistrictPicker: FC<TProps> = (props) => {
  const { value, onChange, left = 6, stepThreeRef } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const [data, setData] = useState<Record<string, TIdNameData[]>>({});
  const notEmpty = Object.values(data).findIndex((item) => item && item.length > 0) > -1;

  const handleSubmit = (val: Record<string, TIdNameData[]>) => {
    onChange && onChange(val);
    setData(val);
    setVisible(false);
  };

  const renderText = () => (
    <div className={styles.showWrap}>
      <div className={styles.showContent}>
        <Space direction="vertical">
          {Object.entries(data).map(([key, resValue]) => (
            <Typography.Text key={key}>
              <Typography.Text strong>{nameObj[key]}</Typography.Text>：
              {resValue.map((o) => o.name).join('、')}
            </Typography.Text>
          ))}
        </Space>
      </div>
      <div className={styles.showBtn} onClick={() => setVisible(true)}>
        编辑
      </div>
    </div>
  );

  useDeepCompareEffect(() => {
    value && setData(value);
  }, [value]);

  return (
    <div className={styles.pickerShowContainer} style={{ paddingLeft: `${left}em` }}>
      <div className={styles.pickerShowBox}>
        {notEmpty ? (
          renderText()
        ) : (
          <span
            className={styles.choseBtn}
            onClick={() => {
              setVisible(true);
            }}
          >
            点击选择
          </span>
        )}
      </div>

      {visible && (
        <PickerModal
          visible={visible}
          data={data}
          onCancel={() => setVisible(false)}
          onSubmit={handleSubmit}
          stepThreeRef={stepThreeRef}
        />
      )}
    </div>
  );
};

export default CommonDistrictPicker;
